#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

#include "decrypt.h"
#include "mqtt_subscriber.h"
#include "report_data.h"

void signal_handler(int signum) {
    mqtt_subscriber_end();
    end_report_data();
    exit(EXIT_SUCCESS);
}

void receive_message(const char* topic, const char* payload, int len) {
    DecryptedData dd;
    int rc;
    if ((rc = decrypt(&dd, payload, len))) {
        printf("Error: decrypt failed, rc = %d\n", rc);
        return;
    }
    print_decrypted_data(&dd);

    WrappedData wd;
    build_wrapped_data(&wd, &dd);
    print_wrapped_data(&wd);

    on_report_receive_data(&wd);
}

int main(int argc, char* argv[])
{
    mqtt_subscriber_init();
    init_report_data();
    set_on_message_callback(receive_message);
    
    signal(SIGINT, signal_handler);

    while (1)
    {
        sleep(1);
        on_loop_sending_report();
    }

    return 0;
}
